#include "downloadHeaders/downloadviewh/historywidget.h"
#include "downloadHeaders/downloadmodelh/historyitemmodel.h"
#include "ui_historywidget.h"
#include "downloadHeaders/downloadviewh/historyitemwidget.h"
#include <QSplitter>
#include <QSqlQuery>
#include <QDesktopServices>
historywidget::historywidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::historywidget)
{
    ui->setupUi(this);
    ui->listWidget->setSpacing(13);
    ui->listWidget->setStyleSheet("QListWidget::item{ "
                                  "margin-right:20px;"
                                  "border-radius:5px;}");

    ui->folder->setIcon(QIcon(":/resource/imgs/folder.png"));
    connect(ui->folder, &QPushButton::clicked, this, &historywidget::openfolder);
    ui->deleteALL->setIcon(QIcon(":/resource/imgs/delete.png"));
    connect(ui->deleteALL, &QPushButton::clicked, this, &historyitemmodel::deleteAll);
    connect(ui->deleteALL, &QPushButton::clicked, this, &historywidget::deleteAllItems);
    showHistory();

}
void historywidget::openfolder()
{
    QDesktopServices::openUrl(QUrl(historyitemmodel::getDownloadDir()));
}
void historywidget::showHistory()
{
    QSqlQuery *query = historyitemmodel::conductQuery();
    int n = 0;
    if (query->last())
    {
       n = query->at() + 1;
    }
    query->first();//重新定位指针到结果集首位
    historyitemwidget **itemwidget = new historyitemwidget*[n];
    for(int i = 0; i < n; i++)
    {
        itemwidget[i] = new historyitemwidget
        (this, query->value(1).toString(), query->value(2).toString(), query->value(3).toString(),query->value(6).toString(), query->value(4).toString());
        itemwidget[i]->widgetItem = new QListWidgetItem();
        connect(itemwidget[i], &historyitemwidget::clicked, this, &historywidget::deleteFromHistory);
        itemwidget[i]->widgetItem->setSizeHint(QSize(731, 135));
        ui->listWidget->insertItem(0, itemwidget[i]->widgetItem);
        ui->listWidget->setItemWidget(itemwidget[i]->widgetItem, itemwidget[i]);
        query->next();
    }
    delete query;

}
void historywidget::deleteFromHistory(historyitemwidget *widget)
{
    ui->listWidget->removeItemWidget(widget->widgetItem);
    delete widget->widgetItem;
}
void historywidget::deleteAllItems()
{
    int n=ui->listWidget->count();//获取item的总数
    //删去所有item
    for(int i=0;i<n;i++)
    {
        /*
             使用takeItem(row)函数将QListWidget中的第row个item移除，
             移除需要使用delete手动释放其在堆上占用的空间
            */
        QListWidgetItem *item = ui->listWidget->takeItem(0); //这里是0，不是i，因为每移除一个item都会导致每个item的row发生变化
        delete item;
    }
}
historywidget::~historywidget()
{
    delete ui;
}
